//
//  XJJuBaoTieZiViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/6/8.
//  Copyright © 2018年 Tzyang. All rights reserved.
//
#pragma mark - XJJUBAoTieZiModel
@interface XJJUBAoTieZiModel:NSObject
/**id*/
@property (nonatomic, copy) NSString *jubaoId;
/**举报内容*/
@property (nonatomic, copy) NSString *name;

@end

@implementation XJJUBAoTieZiModel
+ (NSDictionary *)mj_replacedKeyFromPropertyName {
    return @{@"jubaoId":@"id"};
}
@end
//*****************************************//
#pragma mark - XJJuBaoTieZiHeaderView  写反了应该表尾
typedef void(^XJJuBaoTieZiHeaderViewClickTiJiaoButtonBlock) (void);

@interface XJJuBaoTieZiHeaderView:UIView <UITextViewDelegate>
@property(nonatomic, strong) UITextView *jubaoNeiRongTextView;
@property(nonatomic, strong) UILabel *placeHolerLabel; //请填写举报内容
@property(nonatomic, strong) UIButton *tiJiaoButton; // 提交

/**点击提交按钮*/
@property (nonatomic, copy) XJJuBaoTieZiHeaderViewClickTiJiaoButtonBlock tijiaoButtonBlock;


@end

@implementation XJJuBaoTieZiHeaderView

#pragma mark - 一lazy
- (UITextView *)jubaoNeiRongTextView {
    if (!_jubaoNeiRongTextView) {
        _jubaoNeiRongTextView = [[UITextView alloc] init];
        _jubaoNeiRongTextView.delegate = self;
        _jubaoNeiRongTextView.layer.borderColor = [UIColor blackColor].CGColor;
        _jubaoNeiRongTextView.layer.borderWidth = 1.0;
    }
    return _jubaoNeiRongTextView;
}
- (UILabel *)placeHolerLabel {
    if (!_placeHolerLabel) {
        _placeHolerLabel = [UILabel new];
        _placeHolerLabel.textColor = [UIColor lightGrayColor];
        _placeHolerLabel.text = @"请填写举报内容...";
        
    }
    return _placeHolerLabel;
}
- (UIButton *)tiJiaoButton {
    if (!_tiJiaoButton) {
        
        CGFloat k15 = 15.0;
        
        _tiJiaoButton = [UIButton buttonWithFrame:CGRectMake(k15, 0, KWidth - k15 * 2, 50) target:self action:@selector(tiJiaoButtonAction) bgc:[UIColor yellowColor] title:@"提交"];
    }
    return _tiJiaoButton;
}


#pragma mark - 二 初始化
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
        
    }
    return self;
}
- (void)setupView{
    [self addSubview:self.jubaoNeiRongTextView];
    [self addSubview:self.placeHolerLabel];
    [self addSubview:self.tiJiaoButton];
    
    //此通知主要是为了获取点击空白处回收键盘的处理
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide) name:@"keyboardHide" object:nil];
}

#pragma mark - 三 布局
- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat k15 = 15.0;
    CGFloat k5 = 5.0;
    
    [self.jubaoNeiRongTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).offset(k15);
        make.left.equalTo(self.mas_left).offset(k15);
        make.right.equalTo(self.mas_right).offset(-k15);
        make.height.mas_equalTo(200.0);
    }];
    
    [self.placeHolerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.jubaoNeiRongTextView.mas_top).offset(k5);
        make.left.equalTo(self.jubaoNeiRongTextView.mas_left).offset(k5);
        make.size.mas_equalTo(CGSizeMake(100, 20));
    }];
    
    [self.tiJiaoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.jubaoNeiRongTextView.mas_bottom).offset(k15);
        make.left.equalTo(self.mas_left).offset(k15);
        make.right.equalTo(self.mas_right).offset(-k15);
        make.height.mas_equalTo(50);
    }];
}

// 接收通知回收键盘
- (void)keyboardHide {
    [self.jubaoNeiRongTextView resignFirstResponder];
}


#pragma mark - 四 点击事件
- (void)tiJiaoButtonAction {
    
    if (self.tijiaoButtonBlock) {
        self.tijiaoButtonBlock();
    }
}

#pragma mark - 五 UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    self.placeHolerLabel.hidden = YES;
    
    return YES;
}


@end
//*****************************************//




#import "XJJuBaoTieZiViewController.h"
#import "XJJuBaoSuccessViewController.h" // 举报成功
#import "XJJuBaoTieZiCell.h"


@interface XJJuBaoTieZiViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *selArray; //选中的数据源
@property (nonatomic, strong) XJJuBaoTieZiHeaderView *headerView;

@end

@implementation XJJuBaoTieZiViewController

#pragma mark - 一 lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [_tableView registerNib:[UINib nibWithNibName:@"XJJuBaoTieZiCell" bundle:nil] forCellReuseIdentifier:@"XJJuBaoTieZiCell"];
        
        //给UITableView添加手势,作用:回收键盘
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] init];
        tapGesture.delegate = self;
        [_tableView addGestureRecognizer:tapGesture];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)selArray {
    if (!_selArray) {
        _selArray = [NSMutableArray array];
    }
    return _selArray;
}
- (XJJuBaoTieZiHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[XJJuBaoTieZiHeaderView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 300)];
        
        XJWeakSelf(self);
        _headerView.tijiaoButtonBlock = ^{
          
            NSString *jubaoStr = weakself.headerView.jubaoNeiRongTextView.text;
            
            XJLog(@"%@",jubaoStr);

            
            if (jubaoStr.length > 50) {
                [JRToast showWithText:@"举报内容50个字以内"];
            }else {
                XJLog(@"%@ -- %ld",weakself.self.selArray,weakself.self.selArray.count);
                
                [weakself requestJuBao];
            }
        };
    }
    return _headerView;
}

#pragma mark - 二 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"举报";
    
    self.tableView.frame = CGRectMake(0, XJTopNavH, KWidth, KHeight - XJTopNavH);
    [self.view addSubview:self.tableView];
    
    self.tableView.tableFooterView = self.headerView;
    
    [self requestJuBaoPageData];
}

#pragma mark - 三 UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XJJuBaoTieZiCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XJJuBaoTieZiCell"];
    
    XJJUBAoTieZiModel *model = self.dataArray[indexPath.row];
    [cell configureJuBaoTieName:model.name];
    
    
    cell.btnSelectedBlock = ^(BOOL selected) {
        if (selected) {
            XJLog(@"选中✅✅✅✅✅");
            [self.selArray addObject:model];
        }else {
            XJLog(@"没选中❌❌❌❌❌❌❌❌");
            [self.selArray removeObject:model];
        }
        
        NSLog(@"%@--%ld",self.selArray,self.selArray.count);
    };
    
    return cell;
}

#pragma mark - 四 点击tableView回收键盘
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    //收回键盘
    [[NSNotificationCenter defaultCenter] postNotificationName:@"keyboardHide" object:nil];
    //若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}


#pragma mark - 五 网络请求
// 获取举报内容
- (void)requestJuBaoPageData {
    [XJHttpTool requestInvitationSkipToJuBaoPageSuccessH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            NSArray *complain_stateArr = responseObjc[@"data"][@"complain_state"];
            
            for (NSDictionary *dic in complain_stateArr) {
               XJJUBAoTieZiModel *model = [XJJUBAoTieZiModel mj_objectWithKeyValues:dic];
                
                [self.dataArray addObject:model];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
    } failH:^(NSError *error) {
        XJLog(@"失败:%@",error);
    }];
}

// 举报
- (void)requestJuBao {
    
    if ([NSString isEmptyString:self.invitation_id]) {
        XJLog(@"帖子id为空  可能网络请求错误");
        return;
    }
    
    if (self.selArray.count == 0) {
        [JRToast showWithText:@"请选择举报问题"];
        return;
    }
    
    NSString *text = self.headerView.jubaoNeiRongTextView.text;
    if ([NSString isEmptyString:text]) {
        [JRToast showWithText:@"请填写举报内容"];
        return;
    }
    

    // 请求参数
    // 1.
    
    
    // 2.
    
    NSMutableString *tempStr = [NSMutableString string];
    
    for (XJJUBAoTieZiModel *model in self.selArray) {
        [tempStr appendFormat:@"%@,",model.jubaoId];
    }
    XJLog(@"拼接后的数据:%@",tempStr);
    NSString *complain_state = [NSString stringWithFormat:@"%@",tempStr];

    
    
    NSDictionary *parDic = @{@"invitation_id":self.invitation_id,
                             @"complain_state":complain_state,
                             @"context":text
                             };
    
    
    [XJHttpTool requestInvitationJuBaoTieZiWithDic:parDic successH:^(id responseObjc) {
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            [JRToast showWithText:@"举报成功"];
            
            // 跳转举报成功界面
            XJJuBaoSuccessViewController *succesVC = [[XJJuBaoSuccessViewController alloc] initWithNibName:@"XJJuBaoSuccessViewController" bundle:nil];
            
            [self.navigationController pushViewController:succesVC animated:YES];
        }
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}

@end
